<template>
  <div class="order-Box">
    <div class="flex-box">
      <div style="flex:0.4" class="leftContent">
        <split-vertical title="基本信息"></split-vertical>
        <div class="nameSpace">
          <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="95px" class="demo-ruleForm" label-position="left">
                <el-form-item label="订单分类" prop="orderType">
                  <el-select v-model="ruleForm.orderType" placeholder="请选择"  size="medium" clearable >
                    <el-option
                      v-for="item in orderTypeData"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="订单金额" prop="orderMoney">
                  <el-input v-model="ruleForm.orderMoney" oninput="value=value.replace(/[^\d.]/g,'')"></el-input>
                </el-form-item>
                <el-form-item label="快递方式" prop="expressType">
                  <el-select v-model="ruleForm.expressType" placeholder="请选择"  size="medium" clearable >
                    <el-option
                      v-for="item in expressMethod"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value">
                    </el-option>
                  </el-select>
                </el-form-item>
            <el-row :gutter="5">
              <el-col >
                <el-form-item label="收件人姓名" prop="receiverName">
                  <el-input v-model="ruleForm.receiverName"></el-input>
                </el-form-item>
              </el-col>
              <el-col >
                <el-form-item label="联系方式" prop="receiverPhone">
                  <el-input v-model="ruleForm.receiverPhone"></el-input>
                </el-form-item>
              </el-col>
              <el-col >
                <el-form-item label="地址" prop="receiverAddress" >
                  <el-input type="textarea" v-model="ruleForm.receiverAddress"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col >
                <el-form-item label="备注" prop="orderNote">
                  <el-input type="textarea" v-model="ruleForm.orderNote"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </div>
      <div style="flex:1.2;" class="rightContent">
        <split-vertical title="条件查询"></split-vertical>
        <div class="order-box-header">
          <div class="order-box-content">
            <v-form :formProps="searchForm" ref="form"
                    v-on:handleReset="handleReset"
                    v-on:coverFormData="coverFormData">
            </v-form>
          </div>
        </div>
        <div class="order-table">
          <v-table :tableParams="tableParams" v-on:handleOperation="handleOperation"></v-table>
        </div>
        <div class="block">
          <el-pagination
            @current-change="handleCurrentChange"
            :current-page="pageIndex"
            :page-sizes="[10]"
            :page-size="10"
            layout="total, sizes, prev, pager, next, jumper"
            :total="pageCount">
          </el-pagination>
        </div>
        <div>
      </div>
    </div>
    </div>

    <div class="el-tableData">
      <div class="goodsList">
        <i class="iconfont" style="color:mediumvioletred">&#xe70b;</i>
        <span>商品清单</span>
      </div>
      <el-table
        :data="productList"
        border
        style="width: 100%">
        <el-table-column
          prop="itemCode"
          label="商品编码"
          width="100">
        </el-table-column>
        <el-table-column
          prop="itemSkuName"
          label="商品sku">
        </el-table-column>
        <el-table-column
          prop="purchaseNum"
          label="购买数量"
          width="100">
        </el-table-column>
        <el-table-column
          prop="depotCode"
          label="出仓仓库"
          width="100">
        </el-table-column>
        <el-table-column
          fixed="right"
          label="操作"
          width="120">
          <template slot-scope="scope">
            <el-button
              @click.native.prevent="deleteRow(scope.$index, scope.row)"
              type="text"
              size="small">
              移除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div style="width:100%;text-align: center;margin-top:20px;">
      <el-button type="primary" @click="submitForm('ruleForm')" size="medium">提交</el-button>
      <el-button @click="cancel" size="medium">取消</el-button>
    </div>
    <!--    //弹框-->
    <purchase @submitData="submitData" v-if="show" :rowData="rowData"></purchase>
  </div>
</template>
<script>
  import purchase from "components/base/platformOrder/purchase"
  import VTable from "components/common/PageTable/VTable"
  import SplitVertical from "components/common/SplitVertical"
  import VForm from "components/common/VForm"
  import VButton from "components/common/VButton"
  import {localStorage} from "js/localStorage"
  import {sortData} from "../../../common/js/sort";
  export default {
    components: {
      VTable, purchase, VButton, VForm,SplitVertical
    },
    data() {
      return {
        orderTypeData:[
          {
            value:"A",
            label:"活动订单"
          },{
            value:"B",
            label:"内部购买"
          },{
            value:'C',
            label:"正常订单"
          },{
            value:'D',
            label:'集采订单'
          },{
            value:"E",
            value:"质检订单"
          },{
            value:'F',
            label:"自提订单"
          }],
        expressMethod:[{
          value:'X',
          label:"无"
        },{
          value:"A",
          label:"邮政快递"
        },{
          value:'B',
          label:"顺丰快递"
        },{
          value:'C',
          label:'百世快递'
        },{
          value:"D",
          label:"货拉拉"
        }],
        ruleForm:{
          receiverName:'',
          receiverPhone:'',
          receiverAddress:'',
          orderMoney:'',
          orderNote:'',
          orderType:'',
          expressType:''
        },
        rules:{
          receiverName: [
            { required: true, message: '请输入收件人姓名', trigger: 'blur' },
          ],
          receiverPhone: [
            { required: true, message: '请输入收件人电话', trigger: 'blur' },
            {min: 11, max: 11, message: '请输入正确的手机号', trigger: 'blur'}
          ],
          receiverAddress:[
            { required: true, message: '请输入收件人地址', trigger: 'blur' },
          ],
          orderType:[
            { required: true, message: '请选择订单分类', trigger: 'blur' },
          ],
          orderMoney:[
            { required: true, message: '请输入订单金额', trigger: 'blur' },
          ],
          expressType:[
            { required: true, message: '请选择快递方式', trigger: 'blur' },
          ],
        },
        userId: '',
        add: {},
        list:[],
        pageIndex: 1,
        pageSize: 10,
        pageCount:0,
        rowData: '',
        searchCondition: {},
        productList: [],
        show: false,
        searchForm: {
          col: 4,
          labelWidth: '85px',
          submitBtn: {
            text: '搜索'
          },
          formItemArray: [{
            label: '商品名称',
            prop: 'itemName',
            placeholder: "请输入",
            value: ''
          },{
            label: '商品货号',
            prop: 'itemCode',
            placeholder: "请输入",
            value: ''
          },{
            label: '供应商',
            prop: 'supplyId',
            placeholder: "请选择",
            itemType: 'select',
            options: [],
            value: ''
          },
            {
            label: '仓库名称',
            prop: 'depotCode',
            placeholder: "请选择",
            itemType: 'select',
            options: [],
            value: ''
          }
          ]
        },
        tableParams: {
          dataArray: [],
          showMultiSelection: false,
          columnArray: [
            {label: '供应商', prop: 'supplyName', sortable: false},
            {label: '商品编码', prop: 'itemCode', sortable: false},
            {label: '商品sku', prop: 'itemSkuName', sortable: false},
            {label: '成本价', prop: 'purchasePrice', sortable: false,width:'80'},
            {label: '库存数量', prop: 'storageNum', sortable: false,width:'80'},
            {label: '仓库', prop: 'depotName', sortable: false},

          ],
          rowHandle: {
            view: {
              show: false
            },
            deleted: {
              show: false
            },
            update: {
              show: false
            }
          }
        },

      }
    },
    created() {
      this.init()
    },
    methods: {
      init() {
        // this.add = JSON.parse(this.$route.query.add);
        this.userId = localStorage.get("userID")
        this.getDopot()
        this.getSupplyData()
      },
      cancel() {
        this.$router.push({
          path: '/platform-order'
        })
      },
      //当前页
      handleCurrentChange(val) {
        this.searchCondition['pageIndex'] = val;
        this.query()
      },
      confirm() {
        for(let item of this.list){
          for(let ele of this.productList ){
            if(item.depotName ==ele.depotCode ){
              ele.depotCode=item.id
            }
          }
        }
        let parmas = this.ruleForm;
        parmas['items'] = this.productList
        parmas ['userId'] = this.userId
        let success = data => {
          if (data.code == "OK") {
            this.$message.success(data.msg)
            this.$router.push({
              path:"/platform-order"
            })
          } else {
            this.$message.error(data.msg)
          }
        }
        this.api.internalOrderAdd(parmas, success)
      },
      getDopot() {
        let success = data => {
          if (data.code == "OK") {
            this.list=data.data
            this.searchForm.formItemArray.forEach(item => {
              if (item.prop === 'depotCode') {
                item.options = this.buildExceptKeyAndValue(data.data, "depotName", "id", "label", "value");
              }
            })
          } else {
            this.$message.error(data.msg)
          }
        }
        this.api.erpComplainDepotListAll({}, success)
      },
      getSupplyData() {
        let success = data => {
          if (data.code == "OK") {
            this.searchForm.formItemArray.forEach(item => {
              if (item.prop === 'supplyId') {
                item.options = this.buildExceptKeyAndValue(data.data, "supplyName", "id", "label", "value");
              }
            })
          } else {
            this.$message.error(data.msg)
          }
        }
        this.api.getSupply({}, success)
      },
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.confirm()
          } else {
            return false;
          }
        });
      },
      handleReset(formName) {
        this.$refs.form.resetForm(formName);
      },
      coverFormData(data) {
        this.searchCondition = data;
        this.query()
      },
      query() {
        let param = this.searchCondition;
        if (!param.pageIndex || !param.pageSize) {
          param['pageIndex'] = this.pageIndex;
          param['pageSize'] = this.pageSize;
        }
        let buyBtn = {
          text: '购买',
          show: true,
          type: 'text',
          methodName: 'buy'
        }
        let success = data => {
          if (data.code === 'OK') {
            data.data.sort(sortData("storageNum"))
            this.pageCount = data.pageCount;

            data.data.forEach(ele => {
              ele['handleBtnArray'] = [];
              if (ele.storageNum + '' !== '0') {
                ele['handleBtnArray'] = [buyBtn];
              }else{

              }
            })
            this.tableParams.dataArray = data.data;
          } else {
            this.$message.error(data.msg);
          }
        };
        this.api.internalOrderQuerySupplyItems(param, success)
      },
      submitData(data) {
        this.show = false;
         let b = this.productList.find(item=>item.itemId === data.itemId);
         if (b) {
           this.$message.warning({
             message: '商品已经存在，请不要重复购买',
           });
           return;
         }
        this.productList.push(data);

      },
      deleteRow(index, row) {
        this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.productList.splice(index, 1);
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });

      },
      handleOperation(rowIndex, row, methodName) {
        this.rowData = row
        this.id = row.id
        if (methodName == "buy") {
          this.purchaseMethods()
        }
      },
      purchaseMethods() {
        this.show = true;
      }
    }

  }
</script>

<style lang="scss" scoped>
  .order-Box {
    .flex-box{
      display: flex;
      justify-content: space-between;
      .leftContent{
        background: #fff;
        margin-top: 5px;
        border-left: 2px solid #e8e8e8;
        border-right: 2px solid #e8e8e8;
        border-bottom: 2px solid #e8e8e8;
        .nameSpace{
          margin:5px 10px;
          .el-input{
            width:100%;
            min-width: 200px;
          }
          .el-select{
            width:100%;
            min-width: 200px;
          }
          .el-textarea{
            width:100%;
            min-width: 200px;
          }
        }
      }
      .rightContent{
        padding: 0 10px;
        margin-top: 5px;
        background: #fff;
        border-left: 2px solid #e8e8e8;
        border-right: 2px solid #e8e8e8;
        border-bottom: 2px solid #e8e8e8;
      }
    }

    .order-box-header {
      margin-top:5px;
      padding: 0 10px;
    }
    .goodsList {
      margin-top:4px;
      background: #fff;
      line-height: 30px;
      font-weight: 700;
      padding: 0 10px;
    }
    .order-table {
      margin-top: 10px;
      min-width:250px;
      overflow-x: auto;

    }
    .block{
      padding-top:15px;
      text-align: right;
    }
    .el-tableData{
      border-left: 2px solid #e8e8e8;
      border-right: 2px solid #e8e8e8;
      border-bottom: 2px solid #e8e8e8;
    }
  }
</style>
